package com.qingzhuge.manager.service.impl;

import com.qingzhuge.cache.support.CacheObject;
import com.qingzhuge.exception.ValidatorException;
import com.qingzhuge.manager.dao.SysDeptDao;
import com.qingzhuge.manager.entity.SysDept;
import com.qingzhuge.manager.service.ISysDeptService;
import com.qingzhuge.service.BasePkLongServiceImpl;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.qingzhuge.manager.service.impl.SysDeptServiceImpl.CACHE_NAME;

/**
 * @author : zero.xiao
 * @description :
 * @date :2018/6/12 0012 下午 17:26
 * @modified :
 * @since : 1.0.0
 */
@Service
@CacheConfig(cacheNames = CACHE_NAME)
public class SysDeptServiceImpl extends BasePkLongServiceImpl<SysDeptDao, SysDept> implements ISysDeptService {
    final static String CACHE_NAME = "sysDeptService";

    @Override
    public void delete(SysDept entity) {
        SysDept dept = findOne(entity);
        if (null != dept) {
            List<SysDept> children = baseDao.findByParent(dept);
            if (null != children && children.size() > 0) {
                throw new ValidatorException("信息被下级关联，无法删除");
            } else {
                super.delete(entity);
            }
        }
    }

    @Override
    public void deleteById(Long id) {
        List<SysDept> children = baseDao.findByParent(new SysDept(id));
        if (null != children && children.size() > 0){
            throw new ValidatorException("信息被下级关联，无法删除");
        }else{
            super.deleteById(id);
        }
    }

    @Override
    public List<SysDept> getChildren(Long id){
        CacheObject<List<SysDept>> cacheObject = getCacheObject("children:" + id);
        List<SysDept> children = null;
        if (null != cacheObject){
            children =  cacheObject.getValue();
            if (null == children) {
                children = baseDao.findByParent(new SysDept(id));
                saveCache("children:" + id, children);
            }
        }
        return children;
    }
}
